import React from 'react';
import { PageLoading } from '@ant-design/pro-layout';
import { Redirect } from 'umi';
import { connect } from 'dva';
import Authorized from '@/outter/fr-schema-antd-utils/src/components/Authorized/Authorized';
import { getMatchMenu } from '@umijs/route-utils';
import { stringify } from 'querystring';
import { getMenuData } from '@ant-design/pro-layout';
import NoFoundPage from '@/pages/404';

export class SecurityLayout extends React.Component {
    state = {
        isReady: false,
    };

    componentDidMount() {
        this.setState({
            isReady: true,
        });
        const { dispatch } = this.props;

        if (dispatch) {
            dispatch({
                type: 'user/fetchCurrent',
            });
        }
    }

    render() {
        const { isReady } = this.state;
        const { children, loading, currentUser, route } = this.props; // You can replace it to your authentication rule (such as check token exists)

        // 你可以把它替换成你自己的登录认证规则（比如判断 token 是否存在）
        const isLogin = currentUser && currentUser.id;
        const queryString = stringify({
            redirect: window.location.href,
        });

        if ((!isLogin && loading) || !isReady) {
            return <PageLoading />;
        }

        if (!isLogin && !window.location.pathname.endsWith('/user/login')) {
            return <Redirect to={`/user/login?${queryString}`} />;
        }

        // 判断权限
        const menuData = getMenuData(route.routes);
        const em = getMatchMenu(
            window.location.pathname? window.location.pathname.replace(BASE_PATH, "").replace("/markgos",'').replace("/aiservice",'')  : "/",
            menuData.menuData).pop() || {
            authority: [],
        };
        return (
            <Authorized authority={em.authority} noMatch={NoFoundPage()}>
                {children}
            </Authorized>
        );
    }
}

export default connect(({ user, loading }) => ({
    currentUser: user.currentUser,
    loading: loading.models.user,
}))(SecurityLayout);
